package com.xja.dubbo.controller;

import com.github.pagehelper.PageInfo;
import com.xja.dubbo.entity.*;
import com.xja.dubbo.service.*;
import com.xja.dubbo.util.CookieUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.yaml.snakeyaml.events.Event;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ycz
 * @create 2021-12-18-14:08
 */
@Controller
public class ProductController {

    private Logger logger = LoggerFactory.getLogger(ProductController.class);

    @Reference(url = "dubbo://localhost:20882")
    private UserService userService;

    @Reference(url = "dubbo://localhost:20881")
    private ProductService productService;

    @Reference(url = "dubbo://localhost:20881")
    private ProductCategoryService productCategoryService;

    @Reference(url = "dubbo://localhost:20881")
    private ProductImageService productImageService;

    @Reference(url = "dubbo://localhost:20881")
    private ProductCommentService productCommentService;


    @RequestMapping("productList")
    public String productList(Model model,Integer id, @CookieValue(required = false) String uuid,Integer pageNum){

        try {
            logger.info("展示主页面");

            if(uuid!=null && !"".equals(uuid)){
                Easybuy_user loginUser = userService.findLoginUserFromRedis(uuid);
                model.addAttribute("loginUser",loginUser);
            }
            //获取一级分类
            List<Easybuy_product_category> firstCategory = productCategoryService.findCategoryByPid(0);


            //二级分类
            Map<Integer,List<Easybuy_product_category>> secondMap = new HashMap<>();

            //三级分类
            Map<Integer,List<Easybuy_product_category>> thirdMap = new HashMap<>();

            //获取二级分类
            for (Easybuy_product_category category : firstCategory) {


                //二级分类
                List<Easybuy_product_category> secondCategoryList = productCategoryService.findCategoryByPid(category.getId());

                secondMap.put(category.getId(), secondCategoryList);

                //获取三级分类
                for (Easybuy_product_category secondCategory : secondCategoryList) {

                    List<Easybuy_product_category> thirdCategoryList = productCategoryService.findCategoryByPid(secondCategory.getId());

                    thirdMap.put(secondCategory.getId(), thirdCategoryList);

                }

            }

            //获取商品
            Easybuy_product product = productService.selectByPrimaryKey(id);

            //获取商品图片
            List<Easybuy_product_images> productImagesList = productImageService.selectImage(id);

            //关于评论的内容
            if(pageNum==null){
                pageNum=1;
            }
            PageInfo<Easybuy_product_comment> pageInfo = productCommentService.selectCommentById(id, pageNum);
            Map<String, Object> commMap = productCommentService.selectLevelCommentNumByPid(id);

            Integer zts = Integer.parseInt(commMap.get("zts").toString());
            Integer hps = Integer.parseInt(commMap.get("hps").toString());
            Integer zps = Integer.parseInt(commMap.get("zps").toString());
            Integer cps = Integer.parseInt(commMap.get("cps").toString());

            //计算百分比
            int hpsfb = (int)((hps*1.0/zts)*100);
            int zpsfb = (int)((zps*1.0/zts)*100);
            int cpsfb = (int)((cps*1.0/zts)*100);

            model.addAttribute("product",product);

            model.addAttribute("productImagesList",productImagesList);

            model.addAttribute("pageInfo",pageInfo);

            model.addAttribute("hpsfb",hpsfb);
            model.addAttribute("zpsfb",zpsfb);
            model.addAttribute("cpsfb",cpsfb);

            model.addAttribute("firstCategory",firstCategory);
            model.addAttribute("thirdMap",thirdMap);
            model.addAttribute("secondMap",secondMap);

            return "Product";
        } catch (Exception e) {
            logger.error("展示失败", e);
        }

        return "redirect:error.html";
    }


    @RequestMapping("ensureorder")
    public String ensureorder(Model model,HttpServletRequest request){

        try {
            String uuid = CookieUtil.getCookieValue(request, "uuid");

            //未登录
            if(uuid==null || "".equals(uuid)){
                return "redirect:/login.html";
            }

            Easybuy_user loginUser = userService.findLoginUserFromRedis(uuid);

            //购物车的所有商品，该用户的收货地址，该用户是否是vip
            List<CarShop> carShopList = productService.findProdFromRedis(loginUser);

            //获取地址信息
            List<Easybuy_user_address> userAddressList = userService.selectAddressById(loginUser.getId());

            //是否是vip
            int vipUser = userService.selectVipUser(loginUser.getId());

            //计算总价
            double totalPrice = 0;
            for (CarShop carShop : carShopList) {
                totalPrice += carShop.getBuyNum()*carShop.getProduct().getPrice();
            }

            double vipPrice = totalPrice;
            if (vipUser>0)
                vipPrice = vipPrice*0.8;

            model.addAttribute("carShopList",carShopList);
            model.addAttribute("loginUser",loginUser);
            model.addAttribute("userAddressList",userAddressList);
            model.addAttribute("vipUser",vipUser);
            model.addAttribute("totalPrice",String.format("%.2f", totalPrice));
            model.addAttribute("vipPrice",String.format("%.2f", vipPrice));

            return "BuyCar_Two";

        } catch (Exception e) {
            logger.error("确认订单失败", e);
        }
        return "redirect:error.html";
    }
}
